﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using LynxWiki.Filters;
using LynxWiki.ViewModels;
using LynxWiki.Repository;
using LynxWiki.DomainModel;
using LynxWiki.Search;

namespace LynxWiki.Controllers
{
    [InitializeSimpleMembership]
    public class AttachmentController : Controller
    {
        //
        // GET: /Attachment/

        public ActionResult Index()
        {
            ViewBag.TagCloud = new TagCloud(LuceneSearch.GetTagCount());
            ViewBag.Application = "Version: " + Assembly.GetExecutingAssembly().GetName().Version; 
            AttachmentNamespaceRepository anr = new AttachmentNamespaceRepository();
            List<String> lns = anr.ListNamespaceNames();
            ViewBag.ListNamespacesRead = from s in lns where anr.NamespaceIsAccessible(s, User, "read") select new SelectListItem { Text = s, Value = s, Selected = ("Default" == s ? true : false) };
            ViewBag.ListNamespacesWrite = from s in lns where anr.NamespaceIsAccessible(s, User, "write") select new SelectListItem { Text = s, Value = s, Selected = ("Default" == s ? true : false) };

            AttachmentViewData avd = new AttachmentViewData();
            avd.FileTypeSelected = "5";
            avd.Selections.Add(new FileTypeSelection { ID = 1, FileType = "Images" });
            avd.Selections.Add(new FileTypeSelection { ID = 2, FileType = "Documents" });
            avd.Selections.Add(new FileTypeSelection { ID = 3, FileType = "Videos" });
            avd.Selections.Add(new FileTypeSelection { ID = 4, FileType = "Miscellaneous" });
            avd.Selections.Add(new FileTypeSelection { ID = 5, FileType = "All" });

            return View(avd);
        }

        [HttpPost]
        public async Task<ActionResult> UploadFile(HttpPostedFileBase file, FormCollection fc)
        {
            ViewBag.TagCloud = new TagCloud(LuceneSearch.GetTagCount());
            ViewBag.Application = "Version: " + Assembly.GetExecutingAssembly().GetName().Version;
            AttachmentNamespaceRepository anr = new AttachmentNamespaceRepository(fc["NamespaceSelected"], User);
            AttachmentViewData avd = new AttachmentViewData();
            avd.FileTypeSelected = "5";
            avd.Selections.Add(new FileTypeSelection { ID = 1, FileType = "Images" });
            avd.Selections.Add(new FileTypeSelection { ID = 2, FileType = "Documents" });
            avd.Selections.Add(new FileTypeSelection { ID = 3, FileType = "Videos" });
            avd.Selections.Add(new FileTypeSelection { ID = 4, FileType = "Miscellaneous" });
            avd.Selections.Add(new FileTypeSelection { ID = 5, FileType = "All" });

            string userName = User.Identity.Name;
            if (string.IsNullOrEmpty(userName)) {
                userName = Request.UserHostAddress;
            }

            AttachmentRepository ar = new AttachmentRepository();
            avd.FileUploadResult = await ar.UploadFile(file, fc["VersionNote"], fc["Tags"], fc["ListAllowEditUser"], 
                fc["ListAllowEditRole"], fc["ListDenyReadUser"], fc["ListDenyReadRole"], userName, fc["NamespaceSelected"]);

            List<String> lns = anr.ListNamespaceNames();
            ViewBag.ListNamespacesRead = from s in lns where anr.NamespaceIsAccessible(s, User, "read") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };
            ViewBag.ListNamespacesWrite = from s in lns where anr.NamespaceIsAccessible(s, User, "write") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };

            return View("Index", avd);
        }

        [HttpPost]
        public ActionResult ListFiles(FormCollection fc)
        {
            ViewBag.TagCloud = new TagCloud(LuceneSearch.GetTagCount());
            ViewBag.Application = "Version: " + Assembly.GetExecutingAssembly().GetName().Version;
            AttachmentNamespaceRepository anr = new AttachmentNamespaceRepository(fc["NamespaceSelected"], User);

            AttachmentViewData avd = new AttachmentViewData();
            avd.FileTypeSelected = fc["FileTypeSelected"];
            avd.Selections.Add(new FileTypeSelection { ID = 1, FileType = "Images" });
            avd.Selections.Add(new FileTypeSelection { ID = 2, FileType = "Documents" });
            avd.Selections.Add(new FileTypeSelection { ID = 3, FileType = "Videos" });
            avd.Selections.Add(new FileTypeSelection { ID = 4, FileType = "Miscellaneous" });
            avd.Selections.Add(new FileTypeSelection { ID = 5, FileType = "All" });

            if (anr.NamespaceIsAccessible(fc["NamespaceSelected"], User)) {
                AttachmentRepository ar = new AttachmentRepository();
                List<FileInfo> files = ar.ListAttachmentFiles(Convert.ToInt16(avd.FileTypeSelected), fc["NamespaceSelected"]);
                foreach (FileInfo f in files) {
                    bool updatable = ar.GetCurrentVersionUpdatable(f.FullName, fc["NamespaceSelected"], User);
                    string coUser = ar.GetCurrentVersionCheckedOutUser(f.FullName, fc["NamespaceSelected"]);
                    bool authOK = ar.GetCurrentVersionReadAccess(f.FullName, fc["NamespaceSelected"], User);
                    avd.Files.Add(new AttachFileInfo(f, updatable, coUser, fc["NamespaceSelected"], authOK));
                }
            }
            List<String> lns = anr.ListNamespaceNames();
            ViewBag.ListNamespacesRead = from s in lns where anr.NamespaceIsAccessible(s, User, "read") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };
            ViewBag.ListNamespacesWrite = from s in lns where anr.NamespaceIsAccessible(s, User, "write") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };

            return View("Index", avd);
        }

        [HttpPost]
        public ActionResult CreateNamespace(FormCollection fc)
        {
            AttachmentNamespaceRepository anr = new AttachmentNamespaceRepository(fc["NamespaceSelected"], User);
            AttachmentViewData avd = new AttachmentViewData();
            avd.NamespaceCreatedResult = anr.Add(fc["NamespaceSelected"], fc["ListAllowEditUser"],
                    fc["ListAllowEditRole"], fc["ListDenyReadUser"], fc["ListDenyReadRole"]);

            ViewBag.TagCloud = new TagCloud(LuceneSearch.GetTagCount());
            ViewBag.Application = "Version: " + Assembly.GetExecutingAssembly().GetName().Version;
            List<String> lns = anr.ListNamespaceNames();
            ViewBag.ListNamespacesRead = from s in lns where anr.NamespaceIsAccessible(s, User, "read") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };
            ViewBag.ListNamespacesWrite = from s in lns where anr.NamespaceIsAccessible(s, User, "write") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };

            avd.FileTypeSelected = "5";
            avd.Selections.Add(new FileTypeSelection { ID = 1, FileType = "Images" });
            avd.Selections.Add(new FileTypeSelection { ID = 2, FileType = "Documents" });
            avd.Selections.Add(new FileTypeSelection { ID = 3, FileType = "Videos" });
            avd.Selections.Add(new FileTypeSelection { ID = 4, FileType = "Miscellaneous" });
            avd.Selections.Add(new FileTypeSelection { ID = 5, FileType = "All" });
            
            return View("Index", avd);
        }

        [HttpPost]
        [Authorize(Roles = "WikiAdmin")]
        public ActionResult Delete(FormCollection fc, int fileTypeSelected = 5)
        {
            ViewBag.TagCloud = new TagCloud(LuceneSearch.GetTagCount());
            ViewBag.Application = "Version: " + Assembly.GetExecutingAssembly().GetName().Version;
            AttachmentNamespaceRepository anr = new AttachmentNamespaceRepository(fc["NamespaceSelected"], User);
            AttachmentViewData avd = new AttachmentViewData();
            avd.FileTypeSelected = fileTypeSelected.ToString();
            avd.Selections.Add(new FileTypeSelection { ID = 1, FileType = "Images" });
            avd.Selections.Add(new FileTypeSelection { ID = 2, FileType = "Documents" });
            avd.Selections.Add(new FileTypeSelection { ID = 3, FileType = "Videos" });
            avd.Selections.Add(new FileTypeSelection { ID = 4, FileType = "Miscellaneous" });
            avd.Selections.Add(new FileTypeSelection { ID = 5, FileType = "All" });

            AttachmentRepository ar = new AttachmentRepository();
            avd.FileUploadResult = ar.DeleteAttachmentFile(fc["FileName"], fc["DirectoryPath"]);

            List<FileInfo> files = ar.ListAttachmentFiles(Convert.ToInt16(avd.FileTypeSelected), fc["NamespaceSelected"]);
            foreach (FileInfo f in files) {
                bool updatable = ar.GetCurrentVersionUpdatable(f.FullName, fc["NamespaceSelected"], User);
                string coUser = ar.GetCurrentVersionCheckedOutUser(f.FullName, fc["NamespaceSelected"]);
                bool authOK = ar.GetCurrentVersionReadAccess(f.FullName, fc["NamespaceSelected"], User);
                avd.Files.Add(new AttachFileInfo(f, updatable, coUser, fc["NamespaceSelected"], authOK));
            }

            List<String> lns = anr.ListNamespaceNames();
            ViewBag.ListNamespacesRead = from s in lns where anr.NamespaceIsAccessible(s, User, "read") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };
            ViewBag.ListNamespacesWrite = from s in lns where anr.NamespaceIsAccessible(s, User, "write") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };

            return View("Index", avd);
        }

        [HttpPost]
        [Authorize(Roles = "WikiAdmin")]
        public ActionResult CancelCheckOut(FormCollection fc)
        {
            ViewBag.TagCloud = new TagCloud(LuceneSearch.GetTagCount());
            ViewBag.Application = "Version: " + Assembly.GetExecutingAssembly().GetName().Version;
            AttachmentNamespaceRepository anr = new AttachmentNamespaceRepository(fc["NamespaceSelected"], User);
            AttachmentViewData avd = new AttachmentViewData();
            avd.FileTypeSelected = "5";
            avd.Selections.Add(new FileTypeSelection { ID = 1, FileType = "Images" });
            avd.Selections.Add(new FileTypeSelection { ID = 2, FileType = "Documents" });
            avd.Selections.Add(new FileTypeSelection { ID = 3, FileType = "Videos" });
            avd.Selections.Add(new FileTypeSelection { ID = 4, FileType = "Miscellaneous" });
            avd.Selections.Add(new FileTypeSelection { ID = 5, FileType = "All" });

            AttachmentRepository ar = new AttachmentRepository();
            ar.CheckInAttachment(fc["DirectoryPath"], fc["FileName"]);

            List<String> lns = anr.ListNamespaceNames();
            ViewBag.ListNamespacesRead = from s in lns where anr.NamespaceIsAccessible(s, User, "read") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };
            ViewBag.ListNamespacesWrite = from s in lns where anr.NamespaceIsAccessible(s, User, "write") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };

            return View("Index", avd);
        }

        [HttpPost]
        [Authorize(Roles = "WikiAdmin, WikiUser")]
        public async Task<ActionResult> CheckInUpload(HttpPostedFileBase file, FormCollection fc)
        {
            ViewBag.TagCloud = new TagCloud(LuceneSearch.GetTagCount());
            ViewBag.Application = "Version: " + Assembly.GetExecutingAssembly().GetName().Version;
            AttachmentNamespaceRepository anr = new AttachmentNamespaceRepository(fc["NamespaceSelected"], User);
            AttachmentViewData avd = new AttachmentViewData();
            avd.FileTypeSelected = "5";
            avd.Selections.Add(new FileTypeSelection { ID = 1, FileType = "Images" });
            avd.Selections.Add(new FileTypeSelection { ID = 2, FileType = "Documents" });
            avd.Selections.Add(new FileTypeSelection { ID = 3, FileType = "Videos" });
            avd.Selections.Add(new FileTypeSelection { ID = 4, FileType = "Miscellaneous" });
            avd.Selections.Add(new FileTypeSelection { ID = 5, FileType = "All" });

            List<String> lns = anr.ListNamespaceNames();
            ViewBag.ListNamespacesRead = from s in lns where anr.NamespaceIsAccessible(s, User, "read") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };
            ViewBag.ListNamespacesWrite = from s in lns where anr.NamespaceIsAccessible(s, User, "write") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };

            if (!file.FileName.Contains(fc["FileNameIn"])) {
                avd.FileUploadResult = string.Format("{0} : does not match name of file being uploaded.", fc["FileNameIn"]);

                ViewBag.FileNameIn = fc["FileNameIn"];
                ViewBag.DirectoryPathIn = fc["DirectoryPathIn"];
                ViewBag.NamespaceIn = fc["NamespaceIn"];

                return View("CheckInUpload", avd);
            }
            else {

                AttachmentRepository ar = new AttachmentRepository();
                avd.FileUploadResult = await ar.UploadFile(file, fc["VersionNote"], fc["Tags"], fc["ListAllowEditUser"],
                    fc["ListAllowEditRole"], fc["ListDenyReadUser"], fc["ListDenyReadRole"], User.Identity.Name, fc["NamespaceSelected"]);

                ar.CheckInAttachment(fc["DirectoryPath"], fc["FileName"]);


                return View("Index", avd);
            }
        }

        [HttpPost]
        [Authorize(Roles = "WikiAdmin, WikiUser")]
        public ActionResult CheckIn(FormCollection fc)
        {
            ViewBag.TagCloud = new TagCloud(LuceneSearch.GetTagCount());
            ViewBag.Application = "Version: " + Assembly.GetExecutingAssembly().GetName().Version;
            AttachmentNamespaceRepository anr = new AttachmentNamespaceRepository(fc["NamespaceSelected"], User);
            AttachmentViewData avd = new AttachmentViewData();

            List<String> lns = anr.ListNamespaceNames();
            ViewBag.ListNamespacesRead = from s in lns where anr.NamespaceIsAccessible(s, User, "read") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };
            ViewBag.ListNamespacesWrite = from s in lns where anr.NamespaceIsAccessible(s, User, "write") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };
            ViewBag.FileNameIn = fc["FileName"];
            ViewBag.DirectoryPathIn = fc["DirectoryPath"];
            ViewBag.NamespaceIn = fc["NamespaceSelected"];

            return View("CheckInUpload", avd);
        }

        [HttpPost]
        [Authorize(Roles = "WikiAdmin, WikiUser")]
        public ActionResult CheckOut(FormCollection fc)
        {
            ViewBag.TagCloud = new TagCloud(LuceneSearch.GetTagCount());
            ViewBag.Application = "Version: " + Assembly.GetExecutingAssembly().GetName().Version;
            AttachmentNamespaceRepository anr = new AttachmentNamespaceRepository(fc["NamespaceSelected"], User);
            AttachmentViewData avd = new AttachmentViewData();
            avd.FileTypeSelected = "5";
            avd.Selections.Add(new FileTypeSelection { ID = 1, FileType = "Images" });
            avd.Selections.Add(new FileTypeSelection { ID = 2, FileType = "Documents" });
            avd.Selections.Add(new FileTypeSelection { ID = 3, FileType = "Videos" });
            avd.Selections.Add(new FileTypeSelection { ID = 4, FileType = "Miscellaneous" });
            avd.Selections.Add(new FileTypeSelection { ID = 5, FileType = "All" });

            AttachmentRepository ar = new AttachmentRepository();
            ar.CheckOutAttachment(fc["DirectoryPath"], fc["FileName"], User.Identity.Name);

            List<String> lns = anr.ListNamespaceNames();
            ViewBag.ListNamespacesRead = from s in lns where anr.NamespaceIsAccessible(s, User, "read") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };
            ViewBag.ListNamespacesWrite = from s in lns where anr.NamespaceIsAccessible(s, User, "write") select new SelectListItem { Text = s, Value = s, Selected = (fc["NamespaceSelected"] == s ? true : false) };

            return View("Index", avd);
        }

        [HttpPost]
        public ActionResult ListVersions(FormCollection fc)
        {
            ViewBag.TagCloud = new TagCloud(LuceneSearch.GetTagCount());
            ViewBag.Application = "Version: " + Assembly.GetExecutingAssembly().GetName().Version; 

            AttachmentViewData avd = new AttachmentViewData();
            AttachmentRepository ar = new AttachmentRepository();
            FileInfo f = ar.ListAttachmentFile(fc["FileName"], fc["DirectoryPath"]);
            bool updatable = ar.GetCurrentVersionUpdatable(f.FullName, fc["NamespaceSelected"], User);
            string coUser = ar.GetCurrentVersionCheckedOutUser(f.FullName, fc["NamespaceSelected"]);
            bool authOK = ar.GetCurrentVersionReadAccess(f.FullName, fc["NamespaceSelected"], User);
            avd.Files.Add(new AttachFileInfo(f, updatable, coUser, fc["NamespaceSelected"], authOK));
            avd.Versions = ar.GetVersionList(avd.Files[0].FileName, fc["NamespaceSelected"]);

            return View("ListVersions", avd);

        }
    }
}
